package com.jiantong.standalone;

import com.jiantong.news.model.Quotes;
import com.jiantong.news.service.QuotesWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * Created by niufei on 2017/4/12.
 *
 */
@Slf4j
@Component
public class QuoteJop {

    private static final String URL = "http://zhujia.zhuwang.cc/";
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
    private static final String LI_TAG = "li";
    private static final String HREF_TAG = "href";
    private static final String P_TAG = "p";
    private static final String DIV_TAG = "div";
    private static final String EM_TAG = "em";

    private static final String START_PRICE_DIV_ID = "chart_nav";//报价开始
    private static final String PROVINCE_SHOW_ON_PAGE_CSS_CLASS = "li.sf_list2.fl>a";//显示在界面上的省
    private static final String OTHER_PROVINCE_CSS_CLASS = "li.other>a";//其他省

    private static final String PIG_WSY = "生猪(外三元)";
    private static final String PIG_NSY = "生猪(内三元)";
    private static final String PIG_TZZ = "生猪(土杂猪)";
    private static final String MAIZE = "玉米(15%水分)";
    private static final String SBM = "豆粕(43%蛋白)";
    private static final String PIG_VS_CORN = "猪粮比";

    private static final DateTimeFormatter DFT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    @RpcConsumer
    private QuotesWriteService quotesWriteService;

    @Scheduled(cron = "0 0 8 * * ?")
    public void grabQuoteOnline(){
        try{
            List<Quotes> list = test();
            quotesWriteService.createQuotes(list);
            log.info("create time", DFT.print(DateTime.now()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<Quotes> test() {
        try {
            List<Quotes> list = new ArrayList<>();
            Quotes quotes = null;
            Element dom = null;
            Element bg = null;
            Elements li = null;
            String typeTemp = null , price = null , trendTemp = null ,areaUrl = null;
            Integer type = null ;
            List<Map<Integer , String>> listMap = null;
            while (true){
                listMap = getProvinceUrlMap(URL);
                if (listMap!= null){
                    break;
                }
            }
            Map<Integer, String> map = listMap.get(0);
            Map<Integer , String> map1 = listMap.get(1);
            Set<Integer> set = map.keySet();
            for (Integer key :set) {
                areaUrl =  map.get(key);
                dom = Jsoup.connect(areaUrl).userAgent(USER_AGENT).get();
                bg = dom.getElementById(START_PRICE_DIV_ID);
                li = bg.select(LI_TAG);

                for (Element e : li) {
                    typeTemp = e.select(P_TAG).text();//类型
                    price = e.select(DIV_TAG).text();//价格
                    trendTemp = e.select(EM_TAG).text();//趋势

                    if ("".equals(trendTemp)) {
                        trendTemp = "平稳";
                    }

                    switch (typeTemp) {
                        case PIG_WSY:
                            type = 1;
                            break;
                        case PIG_NSY:
                            type = 2;
                            break;
                        case PIG_TZZ:
                            type = 3;
                            break;
                        case MAIZE:
                            type = 4;
                            break;
                        case SBM:
                            type = 5;
                            break;
                        case PIG_VS_CORN:
                            type = 6;
                            trendTemp = "";
                            break;
                    }
                    quotes = new Quotes();
                    quotes.setType(type);
                    quotes.setDate(new Date());
                    quotes.setPrice(price);
                    quotes.setTrend(trendTemp);
                    quotes.setState(1);
                    quotes.setProvinceId(key);
                    quotes.setProvince(map1.get(key));
                    list.add(quotes);
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private  List<Map<Integer , String>> getProvinceUrlMap(String url){
        Document doc = null;
        try {
            while (true) {
                doc = Jsoup.connect(url).userAgent(USER_AGENT).get();
                if (doc != null) break;
            }
            Elements a1 = doc.select(PROVINCE_SHOW_ON_PAGE_CSS_CLASS);//页面上显示的省
            Elements a2 = doc.select(OTHER_PROVINCE_CSS_CLASS);//其他省
            a1.addAll(a2);
            List<Map<Integer , String>> list = new ArrayList<>();
            Map<Integer, String> map = new LinkedHashMap<>();
            Map<Integer , String> map1 = new LinkedHashMap<>();
            map1.put(0,"全国");
            map.put(0, URL);
            String href = null;
            Integer areaCode = null;

            for (Element e : a1) {
                href = e.attr(HREF_TAG);
                String str  = href.replaceAll("\\D", "");
                areaCode = Integer.parseInt(str.substring(0,str.length()-4));
                map.put(areaCode, href);
                map1.put(areaCode,e.text());
            }
            list.add(0,map);
            list.add(1,map1);
            return list;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }
    }
}
